using homework_2_test_first_development.Exceptions;
using homework_2_test_first_development.Models;

namespace homework_2_test_first_development.Services;

internal static class ReceiptCreator
{
    public static Receipt CreateReceipt(IEnumerable<OrderItem> groupedBarcodes, IEnumerable<Product> products)
    {
        var receipt = new Receipt { TotalPrice = 0m };

        foreach (var item in groupedBarcodes)
        {
            var product = products.FirstOrDefault(p => p.Barcode == item.Barcode);

            if (product is null)
                throw new ProductNotFoundException();

            item.Name = product.Name;
            item.TotalPrice = item.Amount * product.Price;
            item.Price = product.Price;

            receipt.Products = receipt.Products.Append(item);
            receipt.TotalPrice += item.TotalPrice;
        }

        return receipt;
    }
}
